/*
 *    Copyright 2009-2014 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package io.mft.commons.db.mapper;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.mft.commons.db.mapper.builder.ParameterBuilder;
import io.mft.commons.db.mapper.builder.ParameterWrapper;
import io.mft.commons.db.mapper.exception.MapperException;
import io.mft.commons.db.mapper.proxyinvoker.IProxyInvoker;
import io.mft.commons.db.mapper.proxyinvoker.ProxyInvokerType;
import io.mft.commons.db.mapper.transaction.MapperDbOperator;
import io.mft.commons.db.mapper.transaction.MapperTransactionFactory;
/**
 * 数据接口代理类
 * @类型名称：MapperProxy
 * @说明：TODO
 * @创建者: 胡常建  
 * @创建时间: 2018年3月9日 上午10:50:09
 * @修改者: 胡常建  
 * @修改时间: 2018年3月9日 上午10:50:09
 */
public class MapperProxy implements InvocationHandler, Serializable {
	private static final long serialVersionUID = -6424540398559729838L;
	static Logger logger=LoggerFactory.getLogger(MapperProxy.class);
	public MapperProxy() {
	}
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		MapperDbOperator dbOperator = null;
		try {
			Object object = null;
			ParameterWrapper parameter = ParameterBuilder.buildParameter(method, args);
			dbOperator = MapperTransactionFactory.getInstance().buildMapperDbOperator(parameter);
			if (dbOperator!=null) {
				if (!dbOperator.isAuto()) {
					dbOperator.beginTrans();
				}
				Class<?> returnType = method.getReturnType();
				ProxyInvokerType proxyInvokerEnum =parameter.getParameterMetadataWrapper().getProxyInvokerType();
				IProxyInvoker<?> proxyInvoker = proxyInvokerEnum.proxyInvoker();
				if (proxyInvoker == null) {
					throw new MapperException("[" + method.getDeclaringClass().getName() + "." + method.getName()+ "]不支持的返回类型：" + returnType.getName());
				} else {
					object= proxyInvoker.invoke(method, dbOperator.getSession(), parameter.getParameterMetadataWrapper().getSqlParameter(), parameter.getParameter(), parameter);
				}
				return object;
			}else {
				throw new MapperException("");
			}
		} catch (Exception e) {
			throw new MapperException("MapperDbOperator创建失败", e);
		} finally {
			if (dbOperator!=null) {
				if (dbOperator.isAuto()) {
					dbOperator.closeTrans();
				}
			}
		}
	}
	

}
